package com.zshan.clinic.common.response;

import com.zshan.clinic.common.enums.ResultEnum;
import lombok.Data;

import java.util.Collections;
import java.util.Objects;

/**
 * @author lichen
 */
@Data
public class RestResp<T> {


    /**
     * 响应码
     */
    private String code;

    /**
     * 响应消息
     */
    private String msg;

    /**
     * 时间戳
     */
    private long timestamp;

    /**
     * 响应数据
     */
    private T data;


    private RestResp() {
        this.code = ResultEnum.SUCCESS.getValue();
        this.msg = ResultEnum.SUCCESS.getText();
        this.timestamp = System.currentTimeMillis();
    }

    private RestResp(String code, String msg) {
        this.code = code;
        this.msg = msg;
        this.timestamp = System.currentTimeMillis();
    }

    private RestResp(ResultEnum resultEnum) {
        this.code = resultEnum.getValue();
        this.msg = resultEnum.getText();
        this.timestamp = System.currentTimeMillis();
    }

    private RestResp(T data) {
        this();
        this.data = data;
    }

    /**
     * 业务处理失败，有数据返回
     */
    public static <T> RestResp<T> FAIL(String code, String msg) {
        return new RestResp<>(code,msg);
    }

    public static <T> RestResp<T> FAIL(ResultEnum resultEnum) {
        return new RestResp<>(resultEnum);
    }


    /**
     * 业务处理失败，有数据返回
     */
    public static <T> RestResp<T> SYSTEM_FAIL(String msg) {
        return new RestResp<T>(ResultEnum.SYSTEM_FAIL.getValue(),msg);
    }


    public static <T> RestResp<T> BUSINESS_FAIL() {
        return new RestResp<>(ResultEnum.BUSINESS_FAIL);
    }


    /**
     * 业务处理失败，有数据返回
     */
    public static <T> RestResp<T> BUSINESS_FAIL(String msg) {
        return new RestResp<T>(ResultEnum.BUSINESS_FAIL.getValue(),msg);
    }

    public static <T> RestResp<T> UN_LOGIN() {
        return new RestResp<>(ResultEnum.UN_LOGIN);
    }

    public static <T> RestResp<T> UN_LOGIN(String msg) {
        return new RestResp<>(ResultEnum.UN_LOGIN.getValue(),msg);
    }

    /**
     * 业务处理成功,无数据返回
     */
    public static RestResp<Void> SUCCESS() {
        return new RestResp<>();
    }

    /**
     * 业务处理成功，有数据返回
     */
    public static <T> RestResp<T> SUCCESS(T data) {
        return new RestResp<>(data);
    }


    /**
     * 兼容app的判断data不能为空的逻辑
     */
    public static RestResp setMap(RestResp restResp) {
        if(restResp.getData() == null){
            restResp.setData(Collections.emptyMap());
        }
        return restResp;
    }


    /**
     * 判断是否成功
     */
    public boolean isOk() {
        return Objects.equals(this.code, ResultEnum.SUCCESS.getValue());
    }

    public static void main(String[] args) {
        RestResp<Void> restResp = RestResp.BUSINESS_FAIL();
        System.out.println(restResp.toString());
    }

}
